<template>
  <div class="app-container">
    <el-button v-if="checkPermission(['roleadd'])" type="primary" @click="handleAddRole">新增角色</el-button>

    <el-table :data="rolesList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" label="序列" width="220">
        <template slot-scope="scope">
          {{ scope.$index+1 }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="角色名称" width="220">
        <template slot-scope="scope">
          {{ scope.row.roleName }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" width="220">
        <template slot-scope="scope">
          {{ scope.row.status==1? '使用':'禁用' }}

        </template>
      </el-table-column>
      <el-table-column align="header-center" label="角色描述">
        <template slot-scope="scope">
          {{ scope.row.describe }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button v-if="checkPermission(['roleedit'])" type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button v-if="checkPermission(['roledelete'])" type="danger" size="small" @click="handleDelete(scope)">禁用</el-button>
          <el-button v-if="checkPermission(['allocation'])" type="success" size="small" @click="authAdd(scope)">角色分配</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑':'新增'">
      <el-form :model="role" label-width="80px" label-position="left">
        <el-form-item label="角色名称">
          <el-input v-model="role.roleName" placeholder="角色名称" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="role.status">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select></el-form-item>

        <el-form-item label="角色描述">
          <el-input
            v-model="role.describe"
            :autosize="{ minRows: 6, maxRows: 8}"
            type="textarea"
            placeholder="角色描述"
          />
        </el-form-item>
        <el-form-item label="权限">
          <el-tree
            ref="tree"
            :check-strictly="checkStrictly"
            :data="routesData"
            :props="defaultProps"
            default-expand-all
            show-checkbox
            node-key="id"
            class="permission-tree"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="authVisible" title="分配角色">
      <el-form :model="authrole" label-width="80px" label-position="left">
        <el-form-item label="员工">
          <!-- <el-input v-model="empNo" placeholder="员工工号" /> -->
          <el-autocomplete
            v-model="userName"
            class="el-input"
            :fetch-suggestions="userSearchAsync"
            placeholder="请输入内容"
            :trigger-on-focus="false"
            @select="handleSelect"
          />

        </el-form-item>

        <el-form-item label="权限">
          <div style="display:inline">
            <div style="float:left;width:20%;">
              <el-tree
                ref="authtree"
                :check-strictly="checkStrictly"
                :data="routesData"
                :props="authProps"
                default-expand-all
                show-checkbox
                node-key="id"
                class="permission-tree"
              />
            </div>
            <div style="width:50%;float:left;">
              <el-table :data="personlist" border fit highlight-current-row>
                <el-table-column align="center" label="工号" prop="empNo" />
                <el-table-column align="center" label="姓名" prop="userName" />
              </el-table>
              <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fechData" />
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="cancleAuth">取消</el-button>
        <el-button type="primary" @click="confirmUser">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import { deepClone } from '@/utils'
import { getRoutes, fetchRoleList, addRole, deleteRole, updateRole, roleUser } from '@/api/role'
import { getuserbyemp, getuserlistbyRole } from '@/api/user'
import { filterMenuadmin, convertTreeadmin } from '@/router'
import { getToken } from '@/utils/auth'
import checkPermission from '@/utils/permission'
import Pagination from '@/components/Pagination'
// import { resolve } from 'dns'
const defaultRole = {
  key: '',
  name: '',
  description: '',
  status: '',
  routes: []

}

const authdefaultRole = {
  empNo: '',
  roleId: ''
}
export default {
  components: { Pagination },
  data() {
    return {
      role: Object.assign({}, defaultRole),
      authrole: Object.assign({}, authdefaultRole),

      routes: [],
      userId: '',
      userName: '',
      rolesList: [],
      personlist: [],
      total: 20,
      listQuery: {
        page: 1,
        limit: 10,
        roleId: ''
      },
      dialogVisible: false,
      authVisible: false,
      dialogType: 'new',
      authdiaType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title',
        id: 'id'
      },
      authProps: {
        children: 'children',
        label: 'title',
        id: 'id',
        disabled: true
      },
      options: [{
        value: '1',
        label: '使用'
      }, {
        value: '0',
        label: '禁用'
      }]
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    // Mock: get all routes and roles list from server
    this.getRoutes()
    this.getRoles()
  },
  methods: {
    checkPermission,
    async getRoutes() {
      const res = await getRoutes()

      const menus = filterMenuadmin(res.data.menus)
      // console.log(accessedRoutes)
      // const menus = await store.dispatch('permission/getmenus', res.data.menus)
      convertTreeadmin(menus, res.data.menus)
      // console.log(menus)
      this.serviceRoutes = menus
      this.routes = menus
      this.routes = this.generateRoutes(menus)
      // console.log(this.routes)
    },
    async getRoles() {
      const res = await fetchRoleList({ 'Token': getToken() })
      // { 'Token': getToken() }
      this.rolesList = res.data
    },

    // Reshape the routes structure so that it looks the same as the sidebar
    generateRoutes(routes, basePath = '/') {
      const res = []

      for (const route of routes) {
        // skip some route
        if (route.hidden) { continue }
        // console.log(route)
        /*    const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        } */

        const data = {
          path: path.resolve(basePath, route.path),
          title: route.meta && route.meta.title,
          id: route.id
        }

        // recursive child routes
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      return res
    },
    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    handleAddRole() {
      this.role = Object.assign({}, defaultRole)
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    async handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      this.role = deepClone(scope.row)
      console.log(scope.row.roleId)
      const menus = await this.$store.dispatch('permission/fetchMenuslist', { 'roleId': this.role.roleId })

      // console.log(resMenus)
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(menus)
        this.checkStrictly = false
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('确定禁用?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          // console.log(row.roleId)
          await deleteRole({ 'roleId': row.roleId })
          row.status = '0'
          // this.rolesList.splice($index, 1)
          this.$message({
            type: 'success',
            message: 'Delete succed!'
          })
        })
        .catch(err => { console.error(err) })
    },
    generateTree(routes, basePath = '/', checkedKeys) {
      const res = []

      for (const route of routes) {
        const routePath = path.resolve(basePath, route.path)

        // recursive child routes
        if (route.children) {
          route.children = this.generateTree(route.children, routePath, checkedKeys)
        }

        if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
          res.push(route)
        }
      }
      return res
    },
    async authAdd(scope) {
      this.authdiaType = 'new'
      this.authVisible = true
      this.role = deepClone(scope.row)
      const menus = await this.$store.dispatch('permission/fetchMenuslist', { 'roleId': scope.row.roleId })
      this.listQuery.roleId = scope.row.roleId
      this.fechData()
      // console.log(resMenus)
      this.$nextTick(() => {
        this.$refs.authtree.setCheckedKeys(menus)
        this.checkStrictly = false
      })
      // console.log(scope.row.roleId)
    },

    async userSearchAsync(queryString, callback) {
      var list = []
      const { userList } = await getuserbyemp(queryString)
      userList.forEach(r => {
        var tem_obj = {}
        tem_obj.value = r.empNo + '-' + r.userName
        tem_obj.userId = r.userId
        list.push(tem_obj)
      })

      callback(list)
      // console.log(queryString)
    },
    async handleSelect(u) {
      this.userId = u.userId + ''
      // console.log(this.userId)
    },
    async confirmRole() {
      const isEdit = this.dialogType === 'edit'

      /* const checkedKeys = this.$refs.tree.getCheckedKeys()
      this.role.routes = this.generateTree(deepClone(this.serviceRoutes), '/', checkedKeys)
 */
      if (isEdit) {
        const checkedKeys = this.$refs.tree.getCheckedKeys()
        this.role.routes = checkedKeys
        this.role.menuId = this.role.key
        await updateRole({ 'role': this.role })
        for (let index = 0; index < this.rolesList.length; index++) {
          if (this.rolesList[index].roleId === this.role.roleId) {
            this.rolesList.splice(index, 1, Object.assign({}, this.role))
            break
          }
        }
      } else {
        const checkedKeys = this.$refs.tree.getCheckedKeys()
        this.role.routes = checkedKeys
        const { data } = await addRole({ 'role': this.role })
        this.role.key = data.key
        this.rolesList.push(this.role)
      }

      const { description, key, name } = this.role
      this.dialogVisible = false
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: `
            <div>Role Key: ${key}</div>
            <div>Role Name: ${name}</div>
            <div>Description: ${description}</div>
          `,
        type: 'success'
      })
    },
    async cancleAuth() {
      this.userName = ''
      this.userId = ''
      this.authVisible = false
    },
    async confirmUser() {
      const user = this.userId
      await roleUser({ 'userId': user, 'role': this.role })
      this.userName = ''
      this.userId = ''
      this.authVisible = false
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: `            
            <div>分配成功！</div>
          `,
        type: 'success'
      })
    },
    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        // onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ... parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    },
    async fechData() {
      const res = await getuserlistbyRole(this.listQuery)
      this.personlist = res.userList
      this.total = res.total
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
   /*  width: 40% */
  }
}
</style>
